﻿using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Abp.Domain.Uow;
using com.abc.trustpay.client;
using com.abc.trustpay.client.ebus;
using DotNetCore.CAP;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Yozeev.BankService.Models;
using Yozeev.Common.Extensions;

namespace Yozeev.BankService.Clients
{

    public class PaymentClient : IPaymentClient
    {
        private static readonly HttpClient HttpClient = new HttpClient();

        private readonly ICapPublisher _capBus;

        public PaymentClient(ICapPublisher capBus)
        {
            _capBus = capBus;
        }

        public async Task<PaymentRes> MarchantPay(PaymentReqModel req, List<PaymentDetail> details)
        {
            PaymentRequest tPaymentRequest = new PaymentRequest();
            tPaymentRequest.dicOrder = req.ToDictionary();
            for (int i = 0; i < details.Count; i++)
            {
                tPaymentRequest.dic.Add(i + 1, details[i].ToDictionary());
            }

            //传送支付请求并取得支付网址
            tPaymentRequest.postJSONRequest();
            PaymentRes result = new PaymentRes
            {
                ReturnCode = JSON.GetKeyValue("ReturnCode"),
                ErrorMessage = JSON.GetKeyValue("ErrorMessage"),
                OneQRForAll = JSON.GetKeyValue("ReturnCode"),
                PaymentURL = JSON.GetKeyValue("PaymentURL")
            };
            return result;
        }

        /// <summary>
        /// 接收支付结果
        /// </summary>
        /// <returns></returns>
        public async Task<PayResult> PayResult(string MSG)
        {
            PaymentResult tResult = new PaymentResult();
            tResult.init(MSG);
            return new PayResult { Success = tResult.isSuccess(), OrderNo = tResult.getValue("OrderNo") };
        }

        /// <summary>
        /// 微信、支付宝支付订单撤销请求
        /// </summary>
        /// <param name="req"></param>
        /// <returns>若 ReturnCode 返回值为 0000 表示交易成功</returns>
        public async Task<PayCancelRes> PayCancel(PayCancelReqModel req)
        {
            PayCancelRequest cancelRequest = new PayCancelRequest();
            cancelRequest.dicRequest = req.ToDictionary();

            //传送订单撤销请求并取得对账单
            cancelRequest.postJSONRequest();

            PayCancelRes result = new PayCancelRes
            {
                ReturnCode = JSON.GetKeyValue("ReturnCode"),
                ErrorMessage = JSON.GetKeyValue("ErrorMessage"),
                OrderInfo = JSON.GetKeyValue("OrderInfo")
            };

            return result;
        }

        /// <summary>
        /// 订单状态查询 request的QueryDetail为1
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<QueryOrderStatusRes> QueryOrderStatus(QueryOrderReq request)
        {
            QueryOrderRequest tRequest = new QueryOrderRequest();
            tRequest.queryRequest = request.ToDictionary();
            tRequest.postJSONRequest();
            string orderInfo = JSON.GetKeyValue("Order");
            byte[] order = Convert.FromBase64String(orderInfo);
            //1、还原经过base64编码的信息            
            string orderDetail = System.Text.Encoding.GetEncoding("gb2312").GetString(order);
            JSON.setJsonString(orderDetail);

            QueryOrderStatusRes result = new QueryOrderStatusRes 
            {
                ReturnCode = JSON.GetKeyValue("ReturnCode"),
                ErrorMessage = JSON.GetKeyValue("ErrorMessage"),
                OrderDetail = new QueryOrderStatusRes.OrderDetailInfo 
                {
                    PayTypeID = JSON.GetKeyValue("PayTypeID"),
                    OrderNo = JSON.GetKeyValue("OrderNo"),
                    OrderDate = JSON.GetKeyValue("OrderDate"),
                    OrderTime = JSON.GetKeyValue("OrderTime"),
                    OrderAmount = JSON.GetKeyValue("OrderAmount"),
                    Status = JSON.GetKeyValue("Status")
                }
            };

            return result;
        }

        /// <summary>
        /// 微信支付
        /// </summary>
        /// <param name="req">微信支付请求体</param>
        /// <param name="details">订单信息</param>
        /// <returns></returns>
        [UnitOfWork]
        public async Task<PaymentRes> WeichatPay(WeichatPayReq req, List<WeichatOrderItem> details)
        {
            UnifiedPaymentRequest request = new UnifiedPaymentRequest();
            request.dicOrder = req.ToDictionary();
            //for (var i = 0; i < details.Count; i++)
            //{
            //    request.dic.Add(i + 1, details[i].ToDictionary());
            //}

            ////传送支付请求并取得支付网址
            //request.postJSONRequest();

            PaymentRes result = new PaymentRes
            {
                //ReturnCode = JSON.GetKeyValue("ReturnCode"),
                //ErrorMessage = JSON.GetKeyValue("ErrorMessage"),
                //OneQRForAll = JSON.GetKeyValue("ReturnCode"),
                //PaymentURL = JSON.GetKeyValue("PaymentURL")
            };

            await _capBus.PublishAsync("swei.pay.weichat", req.Order.OrderNo);

            return result;
        }
    }
}
